import pandas as pd
import functools
import psutil
import time
import tablib

# 定义一个装饰器来统计函数运行时间
def calculate_statistics(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        start_memory = psutil.Process().memory_info().rss / 1024 / 1024
        result = func(*args, **kwargs)
        end_time = time.time()
        end_memory = psutil.Process().memory_info().rss / 1024 / 1024
        execution_time = end_time - start_time
        memory_used = end_memory - start_memory
        print(f"函数 {func.__name__} 的运行时间为：{execution_time:.6f} 秒")
        print(f"函数 {func.__name__} 的内存占用为：{memory_used:.6f} MB")
        return result
    return wrapper


FilePath = "data/test.xlsx"


@calculate_statistics
def test_pandas():
    df = pd.read_excel(FilePath, sheet_name='Sheet1')
    print(df.shape)


from openpyxl import load_workbook
@calculate_statistics
def test_openpyxl():
    wb = load_workbook(FilePath, read_only=True, data_only=True)
    ws = wb['Sheet1']
    data = []
    for row in ws.iter_rows():
        data.append([cell.value for cell in row])
    df = pd.DataFrame(data)
    print(df.shape)


@calculate_statistics
def test_tablib():
    """测试tablib读取excel的速度"""
    my_dataset = tablib.Databook()
    my_dataset.xlsx = open(FilePath, 'rb').read()
    for dateset in my_dataset.sheets():
        print(dateset.title)
        print(type(dateset))
        df = pd.DataFrame(dateset._data)
        print(df.shape)
# 函数 test_tablib 的运行时间为：224.013345 秒
# 函数 test_tablib 的内存占用为：288.937500 MB


from python_calamine import CalamineWorkbook
@calculate_statistics
def test_calamine():
    """测试calamine读取excel的速度"""
    workbook = CalamineWorkbook.from_path(FilePath)
    df = pd.DataFrame(workbook.get_sheet_by_name('Sheet1').to_python())
    print(df.shape)



if __name__ == '__main__':
    test_calamine()
    pass
    # test_tablib()
    # test_openpyxl()
    # test_pandas()